package cn.cellcom.agent.online.iq.agent;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.j2ee.AgentListener;
import cn.cellcom.agent.online.client.AgentClient;
import cn.cellcom.agent.online.client.Client;
import cn.cellcom.agent.online.handler.TraceHandler;
import cn.cellcom.agent.online.iq.AbstractChainedProcessor;
import cn.cellcom.agent.online.iq.Processor;
import cn.cellcom.agent.online.iq.ProcessorResult;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.pojo.TSession;
import cn.cellcom.agent.struts.form.VisitorForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.MyException;

/**
 * 查询某个访客的会话情况
 * @author zhengyj
 *
 */
public class CrmSessionProcessor extends AbstractChainedProcessor {

	public static final String NAME = "crmSession";

	private Logger log = LoggerFactory.getLogger(this.getClass());

	public CrmSessionProcessor(Processor next) {
		super(next);
	}

	@Override
	public ProcessorResult doProcess(Map<String, AbstractBiz> bizs, Client client, VisitorForm cf) {
		AgentClient ac = (AgentClient) client;
		Map<String, Object> map = new HashMap<String, Object>();
		
		String sid = ac.getIdMap().get(cf.getCid());
		SessionWrapper session = ac.getSession(sid);
		if(session != null) {
			try {
				map.put("trace", TraceHandler.getTraceById(session.getSession().getTrace()));
			} catch (MyException e) {
				log.error(cf.getCid() + " get trace list fail.", e.getException());
			}
			map.put("session", session.getSession());
		}
		try {
			map.put("count", AgentListener.getStaticDao().myCount(
					"select count(*) from " + TSession.class.getSimpleName() + " where pid=? and crm=? and agent is not null",
					new String[] { ac.getPid(), cf.getCid() }));
		} catch (MyException e) {
			log.error(cf.getCid() + " get count fail.", e.getException());
		}
		try {
			//System.out.println(String.valueOf(DT.getToday().getTime()) + "---" + session.getSession().getCrm() + "--" + session.getPid());
			map.put("todayCount", AgentListener.getStaticDao().myCount(
					"select count(*) from " + TSession.class.getSimpleName() + " where pid=? and crm=? and request_time>? and agent is not null",
					new String[] { ac.getPid(), cf.getCid(), String.valueOf(DT.getToday().getTime()) }));
		} catch (MyException e) {
			log.error(cf.getCid() + " get count fail.", e.getException());
		}
		return new ProcessorResult(true, this, map);
		
		/*if (StringUtils.isBlank(sid)) {
			log.error("[{}] get the crm session[{}], but sid is null", ac.getId(), cf.getCid());
			return new ProcessorResult(false, this, null);
		} else {
		}*/
	}

	@Override
	public boolean isAcceptable(VisitorForm message) {
		return NAME.equals(message.getEvent());
	}
}
